import axios from 'axios';
// var instance = axios.create()
// 全局配置
// 超时时间10s
axios.defaults.timeout = 10000;
const reqQueue = {};
// 请求拦截器
// 筛选取消标识
axios.interceptors.request.use(
    function (config) {
        // console.log('configREQ', config)
        // 在发送请求之前做些什么
        // if () {
        config = cancelReq(config);
        // }
        return config;
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);
// 相应拦截器
// 添加响应拦截器
axios.interceptors.response.use(
    function (response) {
        // console.log('response', response);
        // 对响应数据做点什么
        let key = `${response.config.method}_${response.config.headers['Content-Type'] ? response.config.headers['Content-Type'] : ''}_${response.config.url}`;
        if (response.config['key']) {
            key += `_${response.config['key']}`;
        }
        // console.log('key', key);
        if (reqQueue[key]) {
            delete reqQueue[key];
            console.log('reqQueue111', reqQueue);
        }
        return response;
    },
    function (error) {
        // 对响应错误做点什么
        return Promise.reject(error);
    }
);

// 取消请求
function cancelReq(config) {
    if (config['cancel']) {
        const controller = new AbortController();
        // const source = CancelToken.source();
        let key = `${config.method}_${config.headers['Content-Type'] ? config.headers['Content-Type'] : ''}_${config.url}`;
        if (config['key']) {
            key += `_${config['key']}`;
        }
        // console.log('key1', key);
        if (reqQueue[key]) {
            // console.log('reqQueue[key]', reqQueue[key])
            reqQueue[key].abort();
            delete reqQueue[key];
        }
        config.signal = controller.signal
        reqQueue[key] = controller;
        // console.log('reqQueue', reqQueue)
    }
    return config;
}

// 普通请求
const http = {
    get: (url, params = {}, extra) => {
        return axios({
            url: url,
            method: 'get',
            query: params,
            ...extra
        }).catch((error) => {
            console.log(error);
            return new Promise((resolve) => {
                resolve(error)
            })
        });
    },
    // 默认post采用json形式
    post: (url, params = {}, extra = {}) => {
        let conf = {
            headers: {
                'Content-Type': 'application/json'
            }
        };
        conf = Object.assign(conf, extra);
        return axios({
            url: url,
            data: params,
            method: 'post',
            ...conf
        }).catch((error) => {
            console.log(error);
            return new Promise((resolve) => {
                resolve(error)
            })
        });;
    },
    // 表单形式post
    postForm: (url, params = {}, extra = {}) => {
        let conf = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };
        conf = Object.assign(conf, extra);
        return axios({
            url: url,
            data: params,
            method: 'post',
            ...conf
        }).catch((error) => {
            console.log(error);
            return new Promise((resolve) => {
                resolve(error)
            })
        });;
    },
    put: (url, params = {}, extra = {}) => {
        let conf = {
            headers: {
                'Content-Type': 'application/json'
            }
        };
        conf = Object.assign(conf, extra);
        return axios({
            url: url,
            data: params,
            method: 'put',
            ...conf
        }).catch((error) => {
            console.log(error);
            return new Promise((resolve) => {
                resolve(error)
            })
        });;
    },
    putForm: (url, params = {}, extra = {}) => {
        let conf = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };
        conf = Object.assign(conf, extra);
        return axios({
            url: url,
            data: params,
            method: 'put',
            ...conf
        }).catch((error) => {
            console.log(error);
            return new Promise((resolve) => {
                resolve(error)
            })
        });
    },
    delete: (url, params = {}, extra) => {
        return axios({
            url: url,
            method: 'delete',
            params: params,
            ...extra
        });
    },
    GetDownload: (url, params = {}, extra = {}) => {
        let conf = {
            responseType: 'blob'
        };
        conf = Object.assign(conf, extra);
        // 如果在内部处理了axios的结果，则需要套多一层promise，否则外部将得不到信息
        return new Promise((resolve, reject) => {
            axios({
                url: url,
                params: params,
                method: 'get',
                ...conf
            })
                .then((res) => {
                    const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]);
                    // let typeNum = fileName.lastIndexOf('.');

                    // const type = fileName.substring(typeNum + 1);
                    const blob = new Blob([res.data]);
                    const link = document.createElement('a');
                    link.download = fileName;
                    link.style.display = 'none';
                    link.href = URL.createObjectURL(blob);
                    document.body.appendChild(link);
                    link.click();
                    URL.revokeObjectURL(link.href); // 释放URL 对象
                    document.body.removeChild(link);
                    resolve(true);
                })
                .catch((e) => {
                    reject(e.data);
                });
        }).catch((error) => {
            console.log(error);
            return new Promise((resolve) => {
                resolve(error)
            })
        });
    },
    upload: (url, params = {}, extra = {}) => {
        let conf = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        };
        conf = Object.assign(conf, extra);
        return axios({
            url: url,
            data: params,
            method: 'post',
            ...conf
        }).catch((error) => {
            console.log(error);
            return new Promise((resolve) => {
                resolve(error)
            })
        });
    }
};

export default http;
